package com.example.lib_net.interceptor

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import java.nio.charset.StandardCharsets

/*
这里先不用，先写这，等用到的时候再放开
签名拦截器：请求体-》字符串+秘钥盐-》md5加密 请求头x-api-sign签名
 */
class SignInterceptor :Interceptor{
    override fun intercept(chain: Interceptor.Chain): Response {
        val request=chain.request()
        val newBuilder=request.newBuilder()

        //请求体-》字符串
        val s=bodyToString(request)
        val sign=createSign(s,"240111134737B4389719")
        newBuilder.addHeader("x-api-sign",sign)
        return chain.proceed(newBuilder.build())
    }

    fun bodyToString(request: Request):String{
        val buffer=Buffer()
        request.body?.writeTo(buffer)
        return buffer.readUtf8()
    }

    fun createSign(json:String,salt:String):String{
        val buffer=Buffer()
        buffer.write(json.toByteArray(StandardCharsets.UTF_8))
        buffer.write(salt.toByteArray(StandardCharsets.UTF_8))
        return buffer.md5().hex()//十六进制
    }

}